package cli

import (
	"fmt"
	"invitation/internal/application"
	cliContext "invitation/internal/cli/context"
	"invitation/internal/config"
	"invitation/internal/http"

	"github.com/rs/zerolog"
	"github.com/rs/zerolog/log"
)

type RunCMD struct {
	UploadPath string `env:"INVITATION_UPLOAD_PATH,UPLOAD_PATH" type:"path" default:"./uploads" help:"Path to store uploads from files api" group:"storage"`
	ConfigPath string `env:"INVITATION_CONFIG_PATH,CONFIG_PATH" default:"${basepath}/configs" group:"storage"`

	Address string `env:"INVITATION_ADDRESS,ADDRESS" default:":8080" help:"Bind address for the API server" group:"api"`
	CORS    bool   `env:"INVITATION_CORS,CORS" help:"" group:"api"`

	LLMApiKey    string `env:"INVITATION_LLMAPIKEY,LLM_API_KEY" help:"" group:"llm"`
	LLMBaseUrl   string `env:"INVITATION_LLM_BASE_URL,LLM_BASE_URL" help:"" group:"llm"`
	LLMModelName string `env:"INVITATION_LLM_MODEL_NAME,LLM_MODEL_NAME" help:"" group:"llm"`

	DBFilePath string `env:"INVITATION_DB_FILE_PATH,DB_FILE_PATH" default:"${basepath}/data/invitation.db" help:"sqlite db file" group:"storage"`
}

func (r *RunCMD) Run(ctx *cliContext.Context) error {
	opts := []config.AppOption{
		config.WithConfigsDir(r.ConfigPath),
		config.WithUploadDir(r.UploadPath),
		config.WithCors(r.CORS),
		config.WithDebug(zerolog.GlobalLevel() <= zerolog.DebugLevel),
		config.WithLLMApiKey(r.LLMApiKey),
		config.WithLLMBaseUrl(r.LLMBaseUrl),
		config.WithLLMModelName(r.LLMModelName),
		config.WithDBFilePath(r.DBFilePath),
	}
	app, err := application.New(opts...)
	if err != nil {
		return fmt.Errorf("failed basic startup tasks with error %s", err.Error())
	}

	appHTTP, err := http.API(app)
	if err != nil {
		log.Error().Err(err).Msg("error during HTTP App construction")
		return err
	}
	return appHTTP.Listen(r.Address)
}
